//
//  HBPhotoListController.m
//  HBPhotoPicker
//
//  Created by hibo on 2019/5/20.
//  Copyright © 2019 hibo. All rights reserved.
//

#import "HBPhotoListController.h"
#import "HBPhotoManager.h"

@interface HBPhotoListController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic,strong) UICollectionView *collectionview;
@property (nonatomic,strong) UILabel *numLabel;
@property (nonatomic,strong) UIButton *doneButton;
@end

@implementation HBPhotoListController

-(void)cancelBtn{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = _albumModel.title;
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelBtn)];
    self.navigationItem.rightBarButtonItem = right;
}
//设置底部数量及按钮状态
-(void)setBottomState{
    self.numLabel.text = [NSString stringWithFormat:@"已选：%zi/%zi",self.albumModel.selectRows.count,self.albumModel.maxCount];
    if (self.albumModel.selectRows.count>0) {
        self.numLabel.textColor = [UIColor blackColor];
        self.doneButton.backgroundColor = [UIColor colorWithRed:0.14 green:0.51 blue:1.0 alpha:1];
        self.doneButton.enabled = YES;
    }else{
        self.numLabel.textColor = [UIColor grayColor];
        self.doneButton.backgroundColor = [UIColor colorWithRed:0.14 green:0.51 blue:1.0 alpha:0.5];
        self.doneButton.enabled = NO;
    }
}
#pragma mark - 图片资源管理对象
-(void)setAlbumModel:(HBAlbumModel *)albumModel{
    _albumModel = albumModel;
    [self.collectionview reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        CGFloat offset = self.collectionview.contentSize.height-self.collectionview.frame.size.height;
        if(offset>0){
            [self.collectionview setContentOffset:CGPointMake(0, offset)];
        }
    });
}
//选择完成
-(void)doneBtn{
    NSMutableArray *assetList = [NSMutableArray array];
    for (NSInteger i=0;i<self.albumModel.selectRows.count;i++) {
        NSInteger row = [self.albumModel.selectRows[i] integerValue];
        PHAsset *asset = self.albumModel.assetList[row];
        [assetList addObject:asset];
    }
    self.selectResult(assetList);
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 创建collectionview
-(UICollectionView *)collectionview{
    if (_collectionview==nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, HBScreenWidth, HBScreenHeight) collectionViewLayout:layout];
        _collectionview.dataSource = self;
        _collectionview.delegate = self;
        _collectionview.backgroundColor = [UIColor whiteColor];
        _collectionview.scrollEnabled = YES;
        _collectionview.alwaysBounceVertical = YES;
        [_collectionview registerClass:[HBPhotoListCell class] forCellWithReuseIdentifier:@"cell"];
        [self.view addSubview:self.collectionview];
        //底部视图
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, HBScreenHeight-HBBarHEIGHT, HBScreenWidth, HBBarHEIGHT)];
        backView.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.5];
        [self.view addSubview:backView];
        //模糊效果
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
        //必须给effcetView的frame赋值,因为UIVisualEffectView是一个加到UIIamgeView上的子视图.
        effectView.frame = backView.bounds;
        [backView addSubview:effectView];
        //分隔线
        CALayer *lineLayer = [[CALayer alloc] init];
        lineLayer.frame = CGRectMake(0, 0, backView.frame.size.width, 0.5);
        lineLayer.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1].CGColor;
        [backView.layer addSublayer:lineLayer];
        //数量
        _numLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 150, 49)];
        _numLabel.textColor = [UIColor lightGrayColor];
        _numLabel.font = [UIFont systemFontOfSize:16];
        [backView addSubview:_numLabel];
        //完成按钮
        _doneButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _doneButton.frame = CGRectMake(HBScreenWidth-85, 10, 70, 33);
        _doneButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_doneButton setTitle:@"完成" forState:UIControlStateNormal];
        [_doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _doneButton.layer.cornerRadius = 3;
        [backView addSubview:_doneButton];
        [_doneButton addTarget:self action:@selector(doneBtn) forControlEvents:UIControlEventTouchUpInside];
        //设置底部按钮状态
        [self setBottomState];
    }
    return _collectionview;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _albumModel==nil?0:_albumModel.assetList.count;
}
- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    HBPhotoListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    PHAsset *asset = self.albumModel.assetList[indexPath.row];
    cell.asset = asset;
    cell.isSelected = [self.albumModel.selectRows containsObject:@(indexPath.row)];
    __weak typeof(self) weakSelf = self;
    __weak typeof(cell) weakCell = cell;
    cell.selectAction = ^(id result) {
        if ([weakSelf.albumModel.selectRows containsObject:@(indexPath.row)]) {
            [weakSelf.albumModel.selectRows removeObject:@(indexPath.row)];
        }else{
            if (weakSelf.albumModel.selectRows.count>=weakSelf.albumModel.maxCount) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已超出最大选择数" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]];
                [weakSelf presentViewController:alert animated:YES completion:nil];
            }else{
                [weakSelf.albumModel.selectRows addObject:@(indexPath.row)];
            }
        }
        weakCell.isSelected = [weakSelf.albumModel.selectRows containsObject:@(indexPath.row)];
        [weakSelf setBottomState];
    };
    return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((HBScreenWidth-25)/4.0,(HBScreenWidth-25)/4.0);
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 5, 0, 5);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;//如果一组中有多行item,设置两个列的间距
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;//设置两个item的行间距
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(0, HBBarHEIGHT);//设置尾视图大小
}
-(void)dealloc{
    NSLog(@"%@ 被释放",self.class);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


@implementation HBPhotoListCell{
    UIImageView *imageview;
    UIButton *selectButton;
    CALayer *imageLayer;
    UILabel *timeLabel;//视频时间长度
}
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        imageview.contentMode = UIViewContentModeScaleAspectFill;
        imageview.clipsToBounds = YES;
        [self.contentView addSubview:imageview];
        
        selectButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.height-frame.size.height/2, 0, frame.size.height/2, frame.size.height/2)];
        selectButton.clipsToBounds = YES;
        [selectButton setImageEdgeInsets:UIEdgeInsetsMake(2, 20, 20, 2)];
        [selectButton setImage:[UIImage imageNamed:@"hb_select_btn_def"] forState:UIControlStateNormal];
        [selectButton addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:selectButton];
        
        imageLayer = [[CALayer alloc] init];
        imageLayer.frame = imageview.frame;
        imageLayer.hidden = YES;
        imageLayer.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
        [imageview.layer addSublayer:imageLayer];
        
        //视频图片
        timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, frame.size.height-20, frame.size.width-5, 20)];
        timeLabel.textAlignment = NSTextAlignmentRight;
        timeLabel.textColor = [UIColor whiteColor];
        timeLabel.font = [UIFont boldSystemFontOfSize:12];
        [self.contentView addSubview:timeLabel];
    }
    return self;
}
//获取图片显示
-(void)setAsset:(PHAsset *)asset{
    _asset = asset;
    imageview.image = nil;
    [HBPhotoManager getPhotoInfoWithAsset:asset targetSize:CGSizeMake(self.frame.size.width*HBScreenScale, self.frame.size.width*HBScreenScale) result:^(UIImage * _Nonnull image, PHAssetMediaType mediaType) {
        self->imageview.image = image;
        //视频
        NSString *time = @"";
        if (asset.duration<=60) {
            time = [NSString stringWithFormat:@"0:%d",(int)asset.duration];
        }else if(asset.duration<3600){
            time = [NSString stringWithFormat:@"%d:%d",(int)asset.duration/60,(int)asset.duration%60];
        }else{
            time = [NSString stringWithFormat:@"%d:%d:%d",(int)asset.duration/3600,(int)asset.duration%60/60,(int)asset.duration%3600];
        }
        self->timeLabel.text = mediaType == PHAssetMediaTypeVideo?time:@"";
    }];
}
//选择状态
-(void)setIsSelected:(BOOL)isSelected{
    _isSelected = isSelected;
    imageLayer.hidden = !isSelected;
    [selectButton setImage:[UIImage imageNamed:_isSelected?@"hb_select_btn_sel":@"hb_select_btn_def"] forState:UIControlStateNormal];
    if (isSelected) {
        //需要实现的帧动画,这里根据自己需求改动
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
        animation.keyPath = @"transform.scale";
        animation.values = @[@1.0,@1.2,@0.9,@1.0];
        animation.duration = 0.3;
        animation.calculationMode = kCAAnimationCubic;
        //添加动画
        [selectButton.layer addAnimation:animation forKey:nil];
    }
}
//选择
-(void)selectBtn:(UIButton *)button{
    if (_selectAction) {
        _selectAction(@"");
    }
}
@end
